package com.example.leetcode.solution;

import com.example.leetcode.ListNode;

import java.util.ArrayList;
import java.util.List;

public class Solution25 {

    public static ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        if (head.next == null) {
            return head;
        }
        if(k == 1){
            return head;
        }
        ListNode temp = head;
        int index = 1;
        ListNode tail = null;
        List<ListNode> containers = new ArrayList<>();
        containers.add(head);
        while (temp != null && temp.next != null) {
            ListNode current = temp.next;
            containers.add(current);
            ListNode next = null;
            if (current != null) {
                next = current.next;
            }
            temp = current;
            index++;
            if (index % k == 0) {
                for (int i = containers.size() - 1; i >= 0; i--) {
                    ListNode node = containers.get(i);
                    if (i == 0) {
                        tail = node;
                        tail.next = next;
                        temp = next;
                    }
                    if (i == containers.size() - 1) {
                        if (index == k) {
                            head = node;
                        }else{
                            tail.next = node;
                        }
                    }
                    if (i - 1 >= 0) {
                        ListNode listNode = containers.get(i - 1);
                        listNode.next = null;
                        node.next = listNode;
                    }
                }
                index++;
                containers = new ArrayList<>();
                containers.add(temp);
            }
        }
        return head;
    }
}
